package com.dandelion.framework.aop;

import com.dandelion.business.entity.vo.login.resp.AopToken;
import com.dandelion.framework.common.R;
import com.dandelion.framework.common.util.UserUtils;
import com.dandelion.framework.exceptions.ServerException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * web日志方面
 *
 * @author 77088
 * @date 2022/02/16
 */
@Aspect
@Component
public class TokenAspect {

    @Pointcut("execution(public * com.dandelion.business.controller.*.*(..))")
    public void pointCut() {
    }


    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) {

        try {
            //如果不执行这句，会不执行切面的Before方法及controller的业务方法
            Object obj = pjp.proceed();
            AopToken vo = UserUtils.getToken();
            if (vo != null) {
                String accessToken = vo.getAccessToken();
                String refreshToken = vo.getRefreshToken();
                if (obj instanceof R) {
                    R r = (R) obj;
                    r.put("accessToken", accessToken);
                    r.put("refreshToken", refreshToken);
                }
                UserUtils.removeToken();
            }
            return obj;
        } catch (Throwable e) {
            if (e instanceof ServerException) {
                ServerException serverException = (ServerException) e;
                int code = serverException.getCode();
                String msg = serverException.getMsg();
                return R.fail(code, msg);
            }
            return R.fail();
        }
    }
}
